package com.gimi.test_jpa.com.gimi.controller.wqy;


import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.gimi.test_jpa.com.gimi.annotation.ResultInterceptor;
import com.gimi.test_jpa.com.gimi.annotation.Wqy;
import com.gimi.test_jpa.com.gimi.dto.BaseDto;
import com.gimi.test_jpa.com.gimi.entity.wqy.Test;
import com.gimi.test_jpa.com.gimi.feign.ConsumerFeign;
import com.gimi.test_jpa.com.gimi.service.wqy.TestService;
import com.gimi.test_jpa.com.gimi.util.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.*;
import java.util.concurrent.*;


@RestController
@Api(description = "测试")
@RequestMapping("/test")
@Slf4j
@ResultInterceptor
public class TestController {
    @Autowired
    private Test test;
    @Autowired
    private TestService testService;
    @Autowired
    private ConsumerFeign consumerFeign;

    @PostMapping("/wqy")
    @ApiOperation("测试ConfigurationProperties")
    public String getConfig() {
        String jsonStr = JSONUtil.toJsonStr(test);
        log.info(jsonStr);
        return test.getWqy();
    }

    @PostMapping("/uploadPic")
    @ApiOperation("把文件输出到本地磁盘")
    public void uploadPic(MultipartFile file, String url) throws IOException {
        InputStream input = file.getInputStream();  //file 为MultipartFile
        byte[] bs = new byte[1024 * 2];
        // 读取到的数据长度
        int len;
        // 输出的文件流保存至本地
//        OutputStream os = new FileOutputStream("D:\\a.jpg");
//        url=C:\Users\wangqingyu\Desktop\
        OutputStream os = new FileOutputStream(url + file.getOriginalFilename());
        while ((len = input.read(bs)) != -1) {
            os.write(bs, 0, len);
        }
        os.close();
        input.close();
        log.info("===================文件输出完成！======================");
    }

    @PostMapping("/downLoadPic")
    @ApiOperation("下载文件测试")
    public void downLoadPic(MultipartFile file, HttpServletRequest request, HttpServletResponse response) throws IOException {
        InputStream input = file.getInputStream();

        String fileName = file.getOriginalFilename();
        String userAgent = request.getHeader("User-Agent");
        if (userAgent.contains("MSIE") || userAgent.contains("Trident")) {
            //IE浏览器处理
            fileName = java.net.URLEncoder.encode(fileName, "UTF-8");
        } else {
            // 非IE浏览器的处理：
            fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
        }

        response.setContentType("application/octet-stream");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName);
        byte[] bs = new byte[1024 * 2];
        // 读取到的数据长度
        int len;
        // 输出的文件流返回给前端
        OutputStream os = response.getOutputStream();
        while ((len = input.read(bs)) != -1) {
            os.write(bs, 0, len);
        }
        os.close();
        input.close();
    }

    @PostMapping("/downLoadPicByURL")
    @ApiOperation("通过网络链接下载文件")
    public void downLoadPic1(String url, HttpServletRequest request, HttpServletResponse response) throws IOException {
        if (StringUtils.isBlanck(url)) {
            response.getWriter().write("url不能为空！");
            return;
        }
        //通过网络链接获取文件流
        URL urlConnection = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) urlConnection.openConnection();
        conn.setConnectTimeout(3 * 1000);
        // 防止屏蔽程序抓取而返回403错误
        conn.setRequestProperty("User-Agent",
                "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
        conn.connect();
        InputStream input = conn.getInputStream();

        String fileName = "wenjian";

        if (url.endsWith("jpg")) {
            fileName = fileName + ".jpg";
        }
        if (url.endsWith("txt")) {
            fileName = fileName + ".txt";
        }
        if (url.endsWith("docx") || url.endsWith("doc")) {
            fileName = fileName + ".docx";
        }
        if (url.endsWith("pdf")) {
            fileName = fileName + ".pdf";
        }
        if (url.endsWith("xlsx") || url.endsWith("xls")) {
            fileName = fileName + ".xlsx";
        }

        response.setHeader("Content-disposition", "attachment;filename=" + fileName);
        response.setContentType("application/octet-stream");

        byte[] bs = new byte[1024 * 2];
        // 读取到的数据长度
        int len;
        // 输出的文件流返回给前端
        OutputStream os = response.getOutputStream();
        while ((len = input.read(bs)) != -1) {
            os.write(bs, 0, len);
        }
        os.close();
        input.close();
    }

    /**
     * switch测试
     *
     * @param str
     * @return
     */
    @PostMapping("/getStr")
    @ApiOperation("switch测试")
    public String getStr(String str) {
        switch (str) {
            case "天气":
                DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date date = new Date();
                String weather = "天气阴";
                if (new Random().nextInt() % 2 == 0) {
                    weather = "天气晴";
                }
                String s = "现在是" + dateFormat.format(date) + "," + DateUtil.year(date) + "年的第" +
                        DateUtil.dayOfYear(date) + "天！" + weather + "，加油打工人！";
                return s;

            case "wqy":
                return "这是一个帅哥！";
        }
        return "没有找到关键字！";
    }

    @PostMapping("/poolTest")
    @ApiOperation("线程池测试")
    public Object ThreadPoolExecutorTest() {
        ThreadPoolExecutor threadPoolExecutor =
                new ThreadPoolExecutor(5, 20, 0L, TimeUnit.MILLISECONDS,
                        new LinkedBlockingQueue<Runnable>());
//        ExecutorService executorService = Executors.newFixedThreadPool(10); 定长线程池
//        ExecutorService executorService = Executors.newScheduledThreadPool(10); 是唯一一个有延迟执行和周期重复执行的线程池。它的核心线程池固定，非核心线程的数量没有限制，但是闲置时会立即会被回收
//        ExecutorService executorService = Executors.newSingleThreadExecutor(); 单线程线程池
        ExecutorService executorService = Executors.newCachedThreadPool(); //缓存线程池 没有核心线程数，只有最大线程数是Int.Max(values)
        List<Object> list = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            int finalI = i;
            threadPoolExecutor.execute(() -> {
                list.add(finalI);
                System.out.println(Thread.currentThread().getName());
            });
        }

        List<Object> list1 = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            int finalI = i;
            executorService.execute(() -> {
                list1.add(finalI);
                System.out.println(Thread.currentThread().getName());
            });
        }

        HashMap<String, Object> map = new HashMap<>();
        map.put("1", list);
        map.put("2", list1);
        return map;
    }

    @PostMapping("/transactionTest")
    @ApiOperation("事务回滚测试")
    public String transactionTest(String cusId) {
        return testService.transactionTest(cusId);
    }

    @PostMapping("/feignTest")
    @ApiOperation("feign测试")
    public Object transactionTest() {
        return consumerFeign.getObjet();
    }


    public static void main(String[] args) {
        Random r = new Random();
        String str = "";
        for (int a = 0; a < 5; a++) {
            if (a < 4) {
                str += r.nextInt(100) + ",";
            } else {
                str += r.nextInt(100) + "";
            }
        }

        str = "gdsf,fdsfds,fdsfds, ,,,";
        String[] split = str.split(",");
        Arrays.stream(split).forEach((s) -> {
            System.out.println(" ".equals(s));
        });
        System.out.println(split.length);
    }

    @PostMapping("/aspectTest")
    @ApiOperation("aop测试")
    public String aspectTest(String str) {
        return testService.aspectTest(str);
    }

    @PostMapping("/aspectTest2")
    @ApiOperation("aop测试2")
    public String aspectTest2(BaseDto baseDto) {
        return testService.aspectTest2(baseDto);
    }

    @PostMapping("/aspectTest3")
    @ApiOperation("aop测试3")
    public String aspectTest3(BaseDto baseDto, String code) {
        return testService.aspectTest3(baseDto, code);
    }

    @PostMapping("/testErro")
    @ApiOperation("error测试")
    public void testErro() {
//        int i = 1 / 0;
        String str = null;
        str.toString();
    }
}
